package controller

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/gin-gonic/gin"
)

func UploadHandler(c *gin.Context) {
	startTime := time.Now()
	log.Println("Handling upload request")

	// Increase file size limit to 150MB
	err := c.Request.ParseMultipartForm(150 << 20) // 150 MB
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "文件大小超过150MB"})
		return
	}

	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "检索文件时出错"})
		return
	}

	originalFilename := c.PostForm("filename") // 获取文件名

	// Generate unique filename
	filename := generateUniqueFilename(originalFilename)
	filePath := filepath.Join(uploadPath, filename)

	// Create the file for writing
	f, err := os.Create(filePath)
	if err != nil {
		log.Printf("无法创建文件用于写入: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "无法创建文件用于写入"})
		return
	}
	defer f.Close()

	src, err := file.Open()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "无法打开文件"})
		return
	}
	defer src.Close()

	_, err = io.Copy(f, src)
	if err != nil {
		log.Printf("文件写入失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "文件写入失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": fmt.Sprintf("文件上传成功: %s", originalFilename)})
	log.Printf("文件上传成功: %s, 用时: %v", originalFilename, time.Since(startTime))
}
